Passed
Push — develop ( c592f3...b91919 )
by Endre
04:18
created

Router   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 38
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
eloc 32
dl 0
loc 38
ccs 15
cts 15
cp 1
rs 10
c 0
b 0
f 0
wmc 7

5 Functions

Rating   Name   Duplication   Size   Complexity  
A attachTo 0 3 1
A changePage 0 9 2
A onHistoryChange 0 4 1
A updatePage 0 3 1
A initialize 0 6 2
1
import {IObserver} from '../Observer/Observer';
2
3
export interface IPageData {
4
  name: string,
5
  rootUrl: string
6
  url: string,
7
  depth: number
8
}
9
10
export default class Router {
11
  currentPage: IObserver<IPageData | null>;
12
  history: History;
13
14
  constructor(pageObserver: IObserver<IPageData | null>, history: History) {
15 6
    this.currentPage = pageObserver;
16 6
    this.history = history;
17
  }
18
19
  attachTo(window: Window) {
20 3
    window.addEventListener('popstate', this.onHistoryChange.bind(this));
21
  }
22
23
  initialize(): void {
24 3
    if (this.currentPage.value == null) return;
25 1
    const firstPage: IPageData = this.currentPage.value;
26 1
    this.history.replaceState(firstPage, firstPage.name, firstPage.rootUrl);
27 1
    this.updatePage(firstPage);
28
  }
29
30
  changePage(newPage: IPageData): void {
31 2
    const currentPage: IPageData | null = this.currentPage.value;
32 4
    if (currentPage != null && currentPage.name == newPage.name) {
33 1
      return;
34
    }
35
36 1
    this.history.replaceState(newPage, newPage.name, newPage.url);
37 1
    this.updatePage(newPage);
38
  }
39
40
  updatePage(page: IPageData): void {
41 3
    this.currentPage.value = page;
42
  }
43
44
  onHistoryChange(event: PopStateEvent): void {
45 1
    const newPage: IPageData = event.state as IPageData;
46 1
    this.updatePage(newPage);
47
  }
48
}
49